<?php

include(SERVER_ROOT_PATH.'/3rd/taobao/TopSdk.php');
class ml_model_openapiTaobao extends Lib_openapi_abstract {
    public $oauth;
    private  $topclient;
    
    function __construct() { 

        if(!is_object($this->topclient))
            $this->topclient = new TopClient;

        $this->topclient->appkey = ML_TAOBAO_READAPI_APPKEY;
        $this->topclient->secretKey = ML_TAOBAO_READAPI_APPSECRET ;
        $this->authorizeURL=OPENAPI_TAOTAO_APP_AUTHURL;
        $this->topclient->format = "json";
    }
    
    /*
     * 检测返回code
     */
    public function check_auth($code) {

        //登录不授权  解析 字符串

        $url_str=base64_decode($code);

        parse_str($url_str,$info);
        $token=array();
        $token['taobao_user_id']=$info['user_id'];
        $token['taobao_user_nick']=$info['nick'];
        //var_dump($info);var_dump($token);die();
        $session = ml_controller::getSession ();
        $session->setVal ( '3rd_id', $token ['taobao_user_id'] );
        $session->setVal ( '3rd_nick', $token ['taobao_user_nick'] );
        $session->setVal ( 'token_secret', $token['refresh_token'] );
        $session->save ();
        if ($token)
            return $token;
        else
            return false;

        /*
         //oauth2.0  标准版
        $token=$this->getTokenURL(OPENAPI_CALLBACK_URL,$code, 'taobao');
        $token = self::object2Array($token);

        $session = ml_controller::getSession ();
        $session->setVal ( 'access_token', $token ['access_token'] );
        $session->setVal ( '3rd_id', $token ['taobao_user_id'] );
        $session->setVal ( '3rd_nick', $token ['taobao_user_nick'] );
        $session->setVal ( 'token_secret', $token['refresh_token'] );
        $session->save ();
        if ($token)
            return $token;
        else
            return false;
        */
    }

    public function getTokenURL($url,$code,$state=NULL,$view='web',$scope=NULL){
        $params = array();
        $params['code'] =$code;
        $params['client_id'] = $this->topclient->appkey;
        $params['client_secret'] = $this->topclient->secretKey;
        $params['grant_type']='authorization_code';
        $params['redirect_uri'] = $url;
        $params['view'] = $view;
        $params['state'] = $state;
        $params['scope'] = $scope;
        $curl_url="https://oauth.taobao.com/token?" . http_build_query($params);
        $Token=Tool_http::post($curl_url,$params);
        return json_decode($Token);
    }

    
    /*
     * 获取授权用链接
     */
    public function get_auth_url() {
        return $this->getAuthorizeURL(OPENAPI_CALLBACK_URL,'taobao','user');
    }


    function getAuthorizeURL( $url, $state = NULL,$response_type = 'code', $view='web',$scope=NUll) {
        $params = array();
        $params['client_id'] = $this->topclient->appkey;
        $params['redirect_uri'] = $url.'?type=taobao';
        $params['response_type'] = $response_type;
        $params['scope'] = $scope;
        $params['view'] = $view;
        $params['state'] = $state;
        return $this->authorizeURL. "?" . http_build_query($params);
    }
    /*
     * 获取用户基本信息
     */
    public function get_user_info($nick='') {

        if(empty($nick)){
            $session = ml_controller::getSession ();
            $nick=$session->getVal ( '3rd_nick');
        }
        //var_dump($nick);die();
        $req = new UserGetRequest;
        $req->setFields("user_id,nick,sex,buyer_credit,seller_credit,location,created");
        $req->setNick($nick);
        $resp = $this->topclient->execute($req);
        $arr=self::object2Array($resp);
        if(!isset($arr['user'])){
            return false;
        }
        $arr['user']['nickname']=$arr['user']['nick'];
        return $arr['user'];
    }
    
    /*
     * (non-PHPdoc) @see Lib_openapi_abstract::sent_message()
     */
    public function sent_message() {
        // TODO Auto-generated method stub
    
    }

    
    private function _taobaourl2id($url)
    {
        $a = parse_url($url);
        parse_str($a['query'] , $query_var);
        return $query_var['id'];
    }
    public function trans_taobaourl2taokeurl($url)
    {
        $id = $this->_taobaourl2id($url);
        if(!$id)
            return false;

        $req = new TaobaokeItemsConvertRequest;
        $req->setFields("click_url,num_iid,commission,commission_rate,commission_num,commission_volume");
        $req->setNumIids($id);
        $req->setPid(ML_TAOBAO_ALMM_PID);
        $resp = $this->topclient->execute($req);
        
        $this->_set_data($resp->taobaoke_items->taobaoke_item[0]->click_url);
        return true;
    }
    
    //单品
    public function getGoodsInfo($url){
        $id = $this->_taobaourl2id($url);
        if(!$id)
            return false;
        
        $req = new ItemGetRequest;
        $req->setFields("num_iid,title,nick,pic_url,cid,price,type,delist_time,post_fee,score,volume,has_discount,num, is_prepay, promoted_service, ww_status, list_time");
        $req->setNumIid($id);
        $resp = $this->topclient->execute($req);
        $arr=self::object2Array($resp);
        if(!isset($arr['item'])){
            return false;
        }
        $this->_set_data($arr['item']);
        return true;
    }


    /**
     * 获取当前用户的在售商品
     * @param $access_token
     * @return bool
     */
    public function get_my_onsale_goods($access_token,$page=1,$size=30){
        $req = new ItemsOnsaleGetRequest();
        $req->setFields("approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
        $req->setPageNo($page);
        $req->setPageSize($size);
        $resp = $this->topclient->execute($req,$access_token);

        $arr=self::object2Array($resp);
        $this->_set_data($arr);
        return true;
    }


    
    static public function object2Array($rs){
        
        if (is_object($rs)){
            $rs = get_object_vars($rs);
        }
        if(is_array($rs)){
            return array_map(__METHOD__, $rs);
            //var_dump($rs);die();
        }else{
            return $rs;
        }
    }
    
}

/*
if(ml_tool_shop::url2shop($contentData['gd_info']['gd_url']) == 'taobao')
{
    $oApi = new ml_model_openapiTaobao();
    $oApi->trans_taobaourl2taokeurl($contentData['gd_info']['gd_url']);
    $tbk_url = $oApi->get_data();
}
*/